//
//  PariseViewController.m
//  wtshoppingcite
//
//  Created by TW on 15-1-15.
//  Copyright (c) 2015年 TW. All rights reserved.



#import "PariseViewController.h"
#import "BaseTableView.h"
#import "ComplaintCell.h"
#import "NetServiseCommonData.h"
#import "CommentTableView.h"
#import "ShareHeaderView.h"
#import "CommentModel.h"
#import "ShareContentModel.h"
#import "ImgScrollView.h"

@interface PariseViewController ()<UITableViewEventsDelegate,UIActionSheetDelegate,shareHeaderViewDelegate,UITextFieldDelegate,UIScrollViewDelegate,TapImageViewDelegate,ImgScrollViewDelegate>
{
    NSString *pageNum;
}
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)NSArray* dataSourse;
@property(nonatomic,strong)NSArray* commentArray;
@property(nonatomic,strong)CommentTableView *commentTableView;
@property(nonatomic,strong)ShareHeaderView *headerView;
@property(nonatomic,strong)UIActionSheet *actionSheet;
@property(nonatomic,strong)NSMutableArray *dataArray;
@property(nonatomic,strong)NSMutableArray *shareArray;
@property(strong,nonatomic)UIView *imageView;
@property(strong,nonatomic)UITextField *textField;
@property(assign,nonatomic)BOOL isClick;
@property(strong,nonatomic)UIButton *button;
@property(assign,nonatomic)NSInteger pariseNum;
@property(strong,nonatomic)NSMutableDictionary* pariseDic;//点赞数组

@property(strong,nonatomic)UIScrollView *myScrollView;
@property(strong,nonatomic)UIView *markView;
@property(strong,nonatomic)UIView *scrollPanel;
@property(strong,nonatomic)ImgScrollView *lastImgScrollView;
@property(assign,nonatomic)NSInteger currentIndex;

@end

@implementation PariseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setTitleView:@"详情"];
    
    [self setRightButton:@"举报" sel:@selector(reportAction:) viewController:self];
    
    
    _scrollPanel = [[UIView alloc] initWithFrame:self.view.bounds];
    _scrollPanel.backgroundColor = [UIColor clearColor];
    _scrollPanel.alpha = 0;
    [self.view addSubview:_scrollPanel];
    
    _markView = [[UIView alloc] initWithFrame:_scrollPanel.bounds];
    _markView.backgroundColor = MAIN_BLACK_COLOR;
    _markView.alpha = 0.0;
    [_scrollPanel addSubview:_markView];
    
    _myScrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    [_scrollPanel addSubview:_myScrollView];
    _myScrollView.pagingEnabled = YES;
    _myScrollView.delegate = self;
    CGSize contentSize = _myScrollView.contentSize;
    contentSize.height = self.view.bounds.size.height;
    contentSize.width = 320 * 3;
    _myScrollView.contentSize = contentSize;
    
    
    _dataArray = [[NSMutableArray alloc]initWithCapacity:1];
    _shareArray = [[NSMutableArray alloc]initWithCapacity:1];
    
//    [self startDataRequest];
//    [self commentData];
    _pariseDic = [[NSMutableDictionary alloc] init];
    
    pageNum = @"0";
    [self getShareDetailList:NO];
    
    _commentTableView = [[CommentTableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 30) style:UITableViewStylePlain];
    _commentTableView.eventsDelegate = self;
    _commentTableView.data = _commentArray;
    [self.view addSubview:_commentTableView];

    _headerView = [[ShareHeaderView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 260)];
    _headerView.delegate = self;
    _commentTableView.tableHeaderView = _headerView;
    
    
    _imageView = [[UIView alloc]initWithFrame:CGRectMake(0, kHeight - 64 - 40, kWidth, 40)];
    _imageView.backgroundColor = UIColorFromRGB(0xdcdddd);
    _imageView.hidden = YES;
    [self.view addSubview:_imageView];
    
    _textField = [[UITextField alloc]initWithFrame:CGRectMake(5,5, kWidth-70, 30)];
    _textField.borderStyle = UITextBorderStyleRoundedRect;
    _textField.backgroundColor = [UIColor whiteColor];
    _textField.delegate = self;
    [_imageView addSubview:_textField];
    
    _isClick = YES;
    
    _button = [UIButton buttonWithType:UIButtonTypeCustom];
    _button.frame = CGRectMake(_textField.right+5, _textField.top, 50, 30);
    [_button setBackgroundImage:[UIImage imageNamed:@"register_select"] forState:UIControlStateNormal];
    [_button setTitle:@"发送" forState:UIControlStateNormal];
    [_button addTarget:self action:@selector(sendButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [_button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_imageView addSubview:_button];
    
    
    [self registerForKeyboardNotifications];
    // Do any additional setup after loading the view.
}

//发送消息
-(void)sendButtonAction{
    
    __weak PariseViewController *weak_self = self;
    
    if (![APP_DELEGATE isLogin]) {
        
        [APP_DELEGATE pushLoginViewControllerWithStoryBoardIdentifier:@"LoginViewController" pushIn:self];
        
    }else {
    
    
    NSMutableDictionary *listDic = [NSMutableDictionary dictionary];
    
    SetValueForKey(listDic, _shareId, @"shareId");
    SetValueForKey(listDic, [RegisterHelper shareHelper].userId , @"userId");
    SetValueForKey(listDic, _textField.text, @"content");
    
    [NetWorkService byRequestWithAPIPrefix:kBaseAppUrl
                              andAPISuffix:kShareComment
                             andHttpMethod:@"POST"
                             andParameters:listDic
                           andRequestCache:NO
                            andUseParamDic:YES
                       andPostDataEncoding:MKNKPostDataEncodingTypeJSON
                     andRequestFinishBlock:^(BYRequest *request, BYResponse *response) {
                         
                         if (response.isError) {
                             
                             DLog(@"error %@",response.errorMessage);
                             
                         }else{
                             
                             NSDictionary *responseDic = request.responseJSON;
                             DLog(@"成功数据:%@",responseDic);
                             
                             pageNum = @"0";
                             [self getShareDetailList:NO];

                             _isClick = NO;
                             _button.userInteractionEnabled = YES;
                             [_textField resignFirstResponder];
                             
                             [weak_self showToastMessage:@"已发送"];
                             
                             [[NSNotificationCenter defaultCenter] postNotificationName:@"refresh_sharelist_key" object:nil];
                         }
                         
                         }];

    }
//    else if (_isClick == NO){
//        
//        _button.userInteractionEnabled = NO;
//        _textField.userInteractionEnabled = NO;
//        [weak_self showToastMessage:@"您已经给出了评价"];
//        _isClick = YES;
//    }
}

- (void)registerForKeyboardNotifications {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWasShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillBeHidden:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
}


- (void)unregisterForKeyboardNotifications{
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardWillShowNotification
                                                  object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardWillHideNotification
                                                  object:nil];
}

- (void)keyboardWasShow:(NSNotification *)notification {

    
     NSDictionary* info = [notification userInfo];
     CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;//得到鍵盤的高度
    
    CGRect rect = _imageView.frame;
    [UIView animateWithDuration:0.1f animations:^{

         _imageView.frame = CGRectMake(0,kHeight - kbSize.height - rect.size.height - 64, kWidth, 40);
    }];
    
}

- (void)keyboardWillBeHidden:(NSNotification *)notification{
    
    [UIView animateWithDuration:0.3f animations:^{
        _imageView.frame = CGRectMake(0, kHeight - 64 - 40, kWidth, 40);
    }];
}


-(void)btnPressed:(NSInteger)index{
    if (index == 0) {
        if (_imageView.hidden == YES) {
            _imageView.hidden = NO;
        }else{
            _imageView.hidden = YES;
        }
    }else if(index == 1){
        [self getPraiseAdd];
    }
}

#pragma mark 点赞
-(void)getPraiseAdd{
    
    if (APP_DELEGATE.isLogin == NO) {
    
        [self LoginAciton];
        return;
    }
    
     __weak PariseViewController *weak_self = self;
    
    
    NSDictionary* dic = [[NSUserDefaults standardUserDefaults] objectForKey:@"PariseAddKey"];
    _pariseNum = [[dic objectForKey:_shareId] integerValue];
    
    if (_pariseNum < 3) {
        
        NSMutableDictionary *listDic = [NSMutableDictionary dictionary];
        
        SetValueForKey(listDic, _shareId, @"shareId");
        SetValueForKey(listDic, [RegisterHelper shareHelper].userId , @"userId");
        
        [NetWorkService byRequestWithAPIPrefix:kBaseAppUrl
                                  andAPISuffix:kShareAdd
                                 andHttpMethod:@"POST"
                                 andParameters:listDic
                               andRequestCache:NO
                                andUseParamDic:YES
                           andPostDataEncoding:MKNKPostDataEncodingTypeJSON
                         andRequestFinishBlock:^(BYRequest *request, BYResponse *response) {
                             
                             if (response.isError) {
                                 
                                 DLog(@"error %@",response.errorMessage);
                                 
                             }else{
                                 
                                 [_pariseDic setObject:[NSString stringWithFormat:@"%d",(int)++_pariseNum] forKey:_shareId];
                                 [[NSUserDefaults standardUserDefaults] setObject:_pariseDic forKey:@"PariseAddKey"];
                                 [[NSUserDefaults standardUserDefaults] synchronize];
                                 
                                 [_headerView customItemViewWithArray:_shareId];
                                 
                                 NSDictionary *responseDic = request.responseJSON;
                                 DLog(@"成功数据:%@",responseDic);
//                                 [self getShareDetailList:NO];
                                 
//                                 [weak_self showToastMessage:@"已点赞"];
                                 [weak_self showToastMessage:[responseDic objectForKey:@"msg"]];
                             }
                             
                         }];
        
    }else{
        
        [self showToastMessage:@"点赞次数过多"];
    }
}


-(void)textFieldDidEndEditing:(UITextField *)textField{
    
    textField.text = @"";
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    [self registerForKeyboardNotifications];
    [textField resignFirstResponder];
    return YES;
}

#pragma mark  eventsDelegate
- (void)pullUp:(BaseTableView *)baseTableView{
    [self getShareDetailList:YES];
}

- (void)pullDown:(BaseTableView *)baseTableView{
    
    pageNum = @"0";
    [self getShareDetailList:NO];
    
}

#pragma mark getShoppingList 分享详情
-(void)getShareDetailList:(BOOL)isMore{
    
    __weak PariseViewController *weak_self = self;
    NSMutableDictionary *listDic = [NSMutableDictionary dictionary];
    NSString *page = pageNum;
    NSString *pageSize = @"10";
    
    SetValueForKey(listDic, self.shareId, @"shareId");
    SetValueForKey(listDic, page, @"page");
    SetValueForKey(listDic, pageSize, @"pageSize");
   
    _headerView.shareId = _shareId;

    [NetWorkService byRequestWithAPIPrefix:kBaseAppUrl
                                            andAPISuffix:kShareDetailList
                                           andHttpMethod:@"POST"
                                           andParameters:listDic
                                         andRequestCache:NO
                                          andUseParamDic:YES
                                     andPostDataEncoding:MKNKPostDataEncodingTypeJSON
                                   andRequestFinishBlock:^(BYRequest *request, BYResponse *response) {
                                       [_commentTableView doneLoadingTableViewData];
                                       [self performSelector:@selector(dismissLoadImageView) withObject:nil afterDelay:0.5];
                                       
                                       request.requestCache = YES;
                                       
                                       if (response.isError) {
                                           
                                           DLog(@"error %@",response.errorMessage);
                                           
                                       }else{
                                           
                                           NSDictionary *responseDic = request.responseJSON;
                                           DLog(@"成功数据:%@",responseDic);

                                           NSArray *list = [responseDic objectForKey:@"list"];
                                           
                                           NSDictionary *share = [responseDic objectForKey:@"share"];
                                           [_pariseDic setObject:[NSString stringWithFormat:@"%@",[share objectForKey:@"praiseNumber"]] forKey:_shareId];
                                           [[NSUserDefaults standardUserDefaults] setObject:_pariseDic forKey:@"PariseAddKey"];
                                           [[NSUserDefaults standardUserDefaults] synchronize];
                                             _headerView.shareContentModel =[[ShareContentModel alloc]initWithShareContentInfo:share];
                                           
                                           if(_headerView.shareContentModel.imgPaths.count == 0){
                                               CGFloat height = [UIUtility getHeightOfString:_headerView.shareContentModel.content withFont:[UIFont systemFontOfSize:14.0f] withWidth:300];
                                               _headerView.height =height + 100;
                                               
                                           }else{
                                               CGFloat height = [UIUtility getHeightOfString:_headerView.shareContentModel.content withFont:[UIFont systemFontOfSize:14.0f] withWidth:300];
                                            _headerView.height = height + 100 + 126;
                                               
                                           }
                                           
                                           _commentTableView.tableHeaderView = _headerView;
                                           [_headerView reloadInputViews];
                                           
                                           if (list.count < 10) {
                                               _commentTableView.isMore = NO;
                                           }else{
                                               _commentTableView.isMore = YES;
                                               
                                               int currentPage = [pageNum intValue];
                                               pageNum = [NSString stringWithFormat:@"%d",currentPage+1];
                                               
                                           }
                                           if (!isMore) {
                                               [_dataArray removeAllObjects];
                                           }
                                           for (NSDictionary *dic in list) {
                                             
                                               CommentModel *commentModel = [[CommentModel alloc]initWithCommentInfo:dic];
                                               [_dataArray addObject:commentModel];
                                             
                                           }
                                           _commentTableView.data = _dataArray;
                        
                                       }
                                       [_commentTableView reloadData];
                                   }];
    
}

#pragma mark reportAction
-(void)reportAction:(UIButton *)button{
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 20, 20)];
    
    _actionSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:nil destructiveButtonTitle:@"举报" otherButtonTitles:@"取消", nil];
    _actionSheet.tag = 100;
    _actionSheet.delegate = self;
    [_actionSheet showInView:view];
}

#pragma  mark uiactionsheet
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if(actionSheet.tag == 100){
        
        //举报
        if(buttonIndex == 0){
            
        [self getreport];
            
        }
        //取消
        else if(buttonIndex == 1){
         
           actionSheet.hidden = YES;
            
        }
    }else{
        
    }
}

-(void)getreport{
    
}

#pragma arguments 图片缩放delegate
-(void)tappedWithObject:(id)sender{
    
    [self.view bringSubviewToFront:_scrollPanel];
    _scrollPanel.alpha = 1.0;
    
    TapImageView *tmpView = sender;
    _currentIndex = tmpView.tag - 10;
    
    
    //转换后的rect
    CGRect convertRect = [[tmpView superview] convertRect:tmpView.frame toView:self.view];
    
    CGPoint contentOffset = _myScrollView.contentOffset;
    contentOffset.x = _currentIndex*320;
    _myScrollView.contentOffset = contentOffset;
    
    //添加
    [self addSubImgView];
    
    ImgScrollView *tmpImgScrollView = [[ImgScrollView alloc] initWithFrame:(CGRect){contentOffset,_myScrollView.bounds.size}];
    [tmpImgScrollView setContentWithFrame:convertRect];
    [tmpImgScrollView setImage:tmpView.image];
    [_myScrollView addSubview:tmpImgScrollView];
    _myScrollView.contentSize = CGSizeMake(_headerView.shareContentModel.imgPaths.count*SCREEN_WIDTH, SCREEN_HEIGHT);

    tmpImgScrollView.i_delegate = self;
    
    [self performSelector:@selector(setOriginFrame:) withObject:tmpImgScrollView afterDelay:0.1];

}

#pragma mark - custom method 放大
- (void) addSubImgView
{
    
    for (UIView *tmpView in _myScrollView.subviews)
    {
        [tmpView removeFromSuperview];
    }
    
    for (int i = 0; i < _headerView.shareContentModel.imgPaths.count; i ++)
    {
        if (i == _currentIndex)
        {
            continue;
        }
        
        TapImageView *tmpView = (TapImageView *)[self.view viewWithTag:10 + i];
        
        //转换后的rect
        CGRect convertRect = [[tmpView superview] convertRect:tmpView.frame toView:self.view];
        
        ImgScrollView *tmpImgScrollView = [[ImgScrollView alloc] initWithFrame:(CGRect){i*_myScrollView.bounds.size.width,0,_myScrollView.bounds.size}];
        [tmpImgScrollView setContentWithFrame:convertRect];
        [tmpImgScrollView setImage:tmpView.image];
        [_myScrollView addSubview:tmpImgScrollView];
        tmpImgScrollView.i_delegate = self;
        
        [tmpImgScrollView setAnimationRect];
    }
}


- (void) setOriginFrame:(ImgScrollView *) sender
{
    
    [UIView animateWithDuration:0.4 animations:^{
        [sender setAnimationRect];
        _markView.alpha = 1.0;
        [self.navigationController setNavigationBarHidden:YES];
    }];
}


#pragma mark 缩小
- (void) tapImageViewTappedWithObject:(id)sender
{
    [self.navigationController setNavigationBarHidden:NO];
    
    ImgScrollView *tmpImgView = sender;
    [UIView animateWithDuration:0.5 animations:^{
        _markView.alpha = 0;
        [tmpImgView rechangeInitRdct];
    } completion:^(BOOL finished) {
        _scrollPanel.alpha = 0;
    }];
    
}


#pragma mark - scroll delegate
- (void) scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    CGFloat pageWidth = scrollView.frame.size.width;
    _currentIndex = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    

}


- (void)viewWillDisappear:(BOOL)animated
{
    
    [super viewWillDisappear:animated];
    [self unregisterForKeyboardNotifications];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
